﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Core.Extension;
using Core.Mgr._ResMgr;
using CsvHelper;
using UnityEngine;
using UnityEngine.AddressableAssets;

namespace Core.Mgr.Localize
{
    public class LocalizedMgr : SingletonMono<LocalizedMgr>
    {
        [Header("编辑器中使用的字体")] public SystemLanguage editorLanguage = SystemLanguage.ChineseSimplified;
        [Header("所有的字体配置")] public List<FontConfigModel> allFontConfig = new();

        /// <summary>
        /// 所有本地化的字符串
        /// </summary>
        public Dictionary<string, string> AllLocalStr { get; set; } = new();

        /// <summary>
        /// 当前正在使用的语言
        /// </summary>
        public SystemLanguage CurLanguage { get; set; } = NormalLanguage;

        public Font CurFont { get; set; }
        private const SystemLanguage NormalLanguage = SystemLanguage.English;

        /// <summary>
        /// 是否已经初始化
        /// </summary>
        public bool IsInitialized { get; set; } = false;

        public Coroutine OnInit()
        {
            return GameRoot.Ins.StartCoroutine(_OnInit());
        }

        private IEnumerator _OnInit()
        {
            TextAsset textAsset = null;
            CurLanguage = Application.isEditor ? editorLanguage : Application.systemLanguage;
            // 无论是中文还是简体中文还是繁体中文。统一按简体中文算
            if (CurLanguage is SystemLanguage.Chinese or SystemLanguage.ChineseSimplified or
                SystemLanguage.ChineseTraditional)
                CurLanguage = SystemLanguage.ChineseSimplified;
            ResMgr.LoadAsync("Assets/OtherAssets/lang.csv", delegate(TextAsset asset) { textAsset = asset; });
            yield return new WaitUntil(() => textAsset != null);
            using var strReader = new StringReader(textAsset.text);
            using var csvReader = new CsvReader(strReader, CultureInfo.InvariantCulture);
            csvReader.Read();
            // 使用在第几个语言。索引
            var str = CurLanguage.ToString();
            int index = csvReader.Parser.Record.ToList().FindIndex(item => str.Equals(item));
            if (index == -1)
            {
                Debug.LogWarning("多国文档中没有系统语言，使用所配置的默认语言！！！");
                index = csvReader.Parser.Record.ToList().FindIndex(item => item == NormalLanguage.ToString());
                CurLanguage = NormalLanguage;
                if (index == -1)
                {
                    throw new Exception("配置的默认语言在多国文档中不存在！！！");
                }
            }

            while (csvReader.Read())
            {
                var id = csvReader.Parser.Record[0];
                var localStr = csvReader.Parser.Record[index];
                if (AllLocalStr.ContainsKey(id))
                {
                    Debug.LogError($"多国Id必须唯一！！！。请检查配表Id={id}");
                    continue;
                }

                AllLocalStr.Add(id, localStr);
            }

            var assetReferenceFont = allFontConfig.Find(item => item.targetLanguage.Contains(CurLanguage)).fontAsset;
            if (assetReferenceFont == null)
                throw new Exception($"没有配置{NormalLanguage}所使用的字体！！！");
            var asyncHandle = assetReferenceFont.LoadAssetAsync<Font>();
            yield return asyncHandle;
            CurFont = asyncHandle.Result;
            IsInitialized = true;
        }

        /// <summary>
        /// 获得本地化的字符串
        /// </summary>
        /// <param name="id">多国Id</param>
        /// <returns></returns>
        public string GetLocalStr(string id)
        {
            if (AllLocalStr.TryGetValue(id, out string localStr))
            {
                return localStr;
            }

            Debug.LogError($"多国文档中不存在Id={id}");
            return "";
        }
    }


    /// <summary>
    /// 字体配置模型类
    /// </summary>
    [Serializable]
    public class FontConfigModel
    {
        [Header("字体")] public AssetReference fontAsset;

        [Header("字体所对应的目标语言")] public List<SystemLanguage> targetLanguage;
    }
}